package com.ruoyi.project.file.gallery.controller;

import java.time.LocalDate;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.hutool.core.lang.Dict;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.security.ShiroUtils;
import com.ruoyi.common.utils.uuid.IdUtils;
import com.ruoyi.project.file.common.controller.FileController;
import com.ruoyi.project.file.detail.domain.FileDetail;
import com.ruoyi.project.file.detail.service.IFileDetailService;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.dromara.x.file.storage.core.FileInfo;
import org.dromara.x.file.storage.core.FileStorageService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.framework.aspectj.lang.annotation.Log;
import com.ruoyi.framework.aspectj.lang.enums.BusinessType;
import com.ruoyi.project.file.gallery.domain.FileGallery;
import com.ruoyi.project.file.gallery.service.IFileGalleryService;
import com.ruoyi.framework.web.controller.BaseController;
import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.framework.web.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

/**
 * 画廊记录Controller
 *
 * @author zhangqidi
 * @date 2025-08-07
 */
@Controller
@RequestMapping("/file/gallery")
public class FileGalleryController extends BaseController
{
    private static final Logger log = LoggerFactory.getLogger(FileGalleryController.class);

    private String prefix = "file/gallery";

    @Autowired
    private IFileGalleryService fileGalleryService;
    @Autowired
    private FileStorageService fileStorageService;
    @Autowired
    private IFileDetailService fileDetailService;

    @RequiresPermissions("file:gallery:view")
    @GetMapping()
    public String gallery()
    {
        return prefix + "/gallery";
    }

    /**
     * 查询画廊记录列表
     */
    @RequiresPermissions("file:gallery:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(FileGallery fileGallery)
    {
        startPage();
        List<FileGallery> list = fileGalleryService.selectFileGalleryList(fileGallery);
        return getDataTable(list);
    }

    /**
     * 导出画廊记录列表
     */
    @RequiresPermissions("file:gallery:export")
    @Log(title = "画廊记录", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(FileGallery fileGallery)
    {
        List<FileGallery> list = fileGalleryService.selectFileGalleryList(fileGallery);
        ExcelUtil<FileGallery> util = new ExcelUtil<FileGallery>(FileGallery.class);
        return util.exportExcel(list, "画廊记录数据");
    }

    /**
     * 新增画廊记录
     */
    @RequiresPermissions("file:gallery:add")
    @GetMapping("/add")
    public String add()
    {
        return prefix + "/add";
    }

    /**
     * 新增保存画廊记录
     */
    @RequiresPermissions("file:gallery:add")
    @Log(title = "画廊记录", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(FileGallery fileGallery)
    {
        return toAjax(fileGalleryService.insertFileGallery(fileGallery));
    }

    /**
     * 修改画廊记录
     */
    @RequiresPermissions("file:gallery:edit")
    @GetMapping("/edit/{id}")
    public String edit(@PathVariable("id") String id, ModelMap mmap)
    {
        FileGallery fileGallery = fileGalleryService.selectFileGalleryById(id);
        mmap.put("fileGallery", fileGallery);
        return prefix + "/edit";
    }

    /**
     * 修改保存画廊记录
     */
    @RequiresPermissions("file:gallery:edit")
    @Log(title = "画廊记录", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(FileGallery fileGallery)
    {
        return toAjax(fileGalleryService.updateFileGallery(fileGallery));
    }

    /**
     * 删除画廊记录
     */
    @RequiresPermissions("file:gallery:remove")
    @Log(title = "画廊记录", businessType = BusinessType.DELETE)
    @PostMapping( "/remove")
    @ResponseBody
    public AjaxResult remove(String ids)
    {
        return toAjax(fileGalleryService.deleteFileGalleryByIds(ids));
    }


    /**
     * 移动端功能 start...
     */

    /**
     * 移动端画廊的首页（Thymeleaf视图）
     */
    @GetMapping("/mobile/index")
    public String mobileIndex(ModelMap mmap) {
        FileGallery fileGallery = new FileGallery();
        fileGallery.setCreateBy(ShiroUtils.getLoginName());
        //默认只查询第1页
        PageHelper.startPage(1, 10).setReasonable(true);
        List<FileGallery> galleryList = fileGalleryService.selectUserVisibleGalleryList(fileGallery);
        mmap.addAttribute("galleryList", galleryList);
        mmap.addAttribute("currentUser", ShiroUtils.getSysUser());
        return prefix + "/mobile/index";
    }

    /**
     * 移动端分页加载画廊列表：滾動加載
     */
    @PostMapping("/mobile/list")
    @ResponseBody
    public TableDataInfo mobileList(FileGallery fileGallery) {
        // 设置分页
        startPage();
        // 设置当前用户
        fileGallery.setCreateBy(ShiroUtils.getLoginName());
        // 查询用户可见的画廊列表
        List<FileGallery> list = fileGalleryService.selectUserVisibleGalleryList(fileGallery);
        // 返回分页数据
        return getDataTable(list);
    }

    /**
     * 搜索的第一頁
     */
    @GetMapping("/mobile/search")
    @ResponseBody
    public TableDataInfo mobileSearch(@RequestParam("keyword") String keyword) {
        FileGallery fileGallery = new FileGallery();
        fileGallery.setCreateBy(ShiroUtils.getLoginName());
        if (StringUtils.isNotEmpty(keyword)){
            fileGallery.setTitle(keyword);
        }
        //默认只查询第1页
        PageHelper.startPage(1, 10).setReasonable(true);
        List<FileGallery> list = fileGalleryService.selectUserVisibleGalleryList(fileGallery);
        // 返回分页数据
        return getDataTable(list);
    }

    /**
     * 获取画廊文件（用于AJAX加载）
     */
    @GetMapping("/mobile/files/{galleryId}/{galleryType}")
    @ResponseBody
    public AjaxResult getGalleryFiles(@PathVariable("galleryId") String galleryId,
                                     @PathVariable("galleryType") Integer galleryType) {
        List<FileDetail> files = fileGalleryService.selectGalleryFiles(galleryId, galleryType);
        // 根据attr中的order值对文件进行排序
        sortFilesByOrder(files);
        return AjaxResult.success(files);
    }


    /**
     * 新增保存手机上传的画廊
     * @param title
     * @param recordDate
     * @param shareType
     * @param content
     * @param isVideo
     * @param files
     * @return
     */
    @PostMapping("/mobile/save")
    @ResponseBody
    public AjaxResult saveMobileGallery(String title, String recordDate, String shareType, String content, Boolean isVideo, MultipartFile[] files) {
        try {
            String currentUser = ShiroUtils.getLoginName();
            return fileGalleryService.saveMobileGallery(title, recordDate, shareType, content, isVideo, files, currentUser);
        } catch (Exception e) {
            log.error("保存失败: ", e);
            return AjaxResult.error("保存失败: " + e.getMessage());
        }
    }


    /**
     * 修改保存手机上传的画廊
     * @param id
     * @param title
     * @param recordDate
     * @param shareType
     * @param content
     * @param isVideo
     * @param files 新增文件（目前只能是图片）
     * @param deletedFileIds 删除的文件id
     * @param fullSortedOrder 所有文件的排序顺序（包含已有文件id和新文件tempId）
     * @return
     */
    @PostMapping("/mobile/update")
    @ResponseBody
    public AjaxResult updateMobileGallery(String id, String title, String recordDate, String shareType,
                                          String content, Boolean isVideo, MultipartFile[] files,
                                          String deletedFileIds, String fullSortedOrder) {
        try {
            String currentUser = ShiroUtils.getLoginName();
            return fileGalleryService.updateMobileGallery(id, title, recordDate, shareType,
                    content, isVideo, files, deletedFileIds, fullSortedOrder, currentUser);
        } catch (Exception e) {
            log.error("更新画廊失败: ", e);
            return AjaxResult.error("更新失败: " + e.getMessage());
        }
    }

    /**
     * 获取画廊详情（移动端）
     */
    @GetMapping("/mobile/detail/{galleryId}")
    @ResponseBody
    public AjaxResult getMobileGalleryDetail(@PathVariable("galleryId") String galleryId) {
        try {
            // 查询画廊基本信息
            FileGallery gallery = fileGalleryService.selectFileGalleryById(galleryId);
            if (gallery == null) {
                return AjaxResult.error("画廊不存在");
            }

            // 验证当前用户是否有权限查看该画廊
            String currentUser = ShiroUtils.getLoginName();
            // 如果画廊不是公开的，且不是当前用户创建的，则无权查看
            if (gallery.getShareType() != 2 && !currentUser.equals(gallery.getCreateBy())) {
                return AjaxResult.error("无权限查看该画廊");
            }

            // 查询画廊中的文件
            List<FileDetail> files = fileGalleryService.selectGalleryFiles(galleryId, gallery.getGalleryType().intValue());
            // 根据attr中的order值对文件进行排序
            sortFilesByOrder(files);

            // 构建返回结果
            Map<String, Object> result = new HashMap<>();
            result.put("gallery", gallery);
            result.put("files", files);

            return AjaxResult.success(result);
        } catch (Exception e) {
            log.error("获取画廊详情失败: ", e);
            return AjaxResult.error("获取画廊详情失败: " + e.getMessage());
        }
    }

    /**
     * 根据文件的attr属性中的order值对文件列表进行排序
     * @param files 文件列表
     */
    private void sortFilesByOrder(List<FileDetail> files) {
        if (files == null || files.isEmpty()) {
            return;
        }

        files.sort((file1, file2) -> {
            Dict dict1 = Dict.parse(JSONObject.parseObject(file1.getAttr()));
            Dict dict2 = Dict.parse(JSONObject.parseObject(file2.getAttr()));
            Integer order1 = dict1.getInt("order");
            if (order1 == null) {
                order1 = 0;
            }
            Integer order2 = dict2.getInt("order");
            if (order2 == null) {
                order2 = 0;
            }
            return order1.compareTo(order2);
        });
    }

    /**
     * 删除移动端画廊记录
     */
    @PostMapping("/mobile/delete/{galleryId}")
    @ResponseBody
    public AjaxResult deleteMobileGallery(@PathVariable("galleryId") String galleryId) {
        try {
            String currentUser = ShiroUtils.getLoginName();
            return fileGalleryService.deleteMobileGallery(galleryId, currentUser);
        } catch (Exception e) {
            log.error("删除画廊失败: ", e);
            return AjaxResult.error("删除失败: " + e.getMessage());
        }
    }

}
